package in.hbb20.countrycodepickerproject.fragment;

import com.hbb20.CountryCodePicker;
import com.hbb20.FocusLine;
import in.hbb20.countrycodepickerproject.ResourceTable;
import com.hbb20.utils.Toast;
import ohos.agp.components.*;
import ohos.app.Context;

public class CustomMasterFragment extends Fragment {

    private TextField editTextCountryCustomMaster;
    private Button buttonSetCustomMaster;
    private CountryCodePicker ccp;
    private Button buttonNext;

    public CustomMasterFragment(Context context) {
        super(context);
    }

    @Override
    protected Component onCreateView(LayoutScatter layoutScatter, ComponentContainer container) {
        return layoutScatter.parse(ResourceTable.Layout_fragment_custom_master_list, null, false);
    }

    @Override
    protected void onViewCreate() {
        assignViews();
        editTextWatcher();
        addClickListeners();
    }

    private void assignViews() {
        ScrollView scrollview = (ScrollView) findComponentById(ResourceTable.Id_scrollview);
        editTextCountryCustomMaster = (TextField) findComponentById(ResourceTable.Id_editText_countryPreference);
        FocusLine.drawFocusLine(editTextCountryCustomMaster, findComponentById(ResourceTable.Id_component_line),scrollview);
        ccp = (CountryCodePicker) findComponentById(ResourceTable.Id_ccp);
        buttonSetCustomMaster = (Button) findComponentById(ResourceTable.Id_button_setCustomMaster);
        buttonNext = (Button) findComponentById(ResourceTable.Id_button_next);
        Text  defText1 = (Text) findComponentById(ResourceTable.Id_text_def1);
        String text = "<com.hbb20.CountryCodePicker \n ohos:id=\"$+id:ccp\" \n ohos:width=\"match_content\" \n ohos:height=\"match_content\" \n app:ccp_defaultNameCode=\"US\" \n app:ccp_customMasterCountries=\"US,IN,NZ,BD,PL,RO,ZW\"/>";
        defText1.setText(text);
    }

    private void addClickListeners() {

        buttonSetCustomMaster.setClickedListener(component -> {
            String customMasterCountries = editTextCountryCustomMaster.getText().toString();
            ccp.setCustomMasterCountries(customMasterCountries);
            Toast.showShort(mContext, "Master list has been changed. Tap on ccp to see the changes.");
        });

        buttonNext.setClickedListener(component -> {
            if (mChangeFragment != null) {
                mChangeFragment.changeFragment(mChangeFragment.getCurrentPage() + 1);
            }
        });
    }

    private void editTextWatcher() {

        editTextCountryCustomMaster.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String s, int i, int i1, int i2) {
                String text = "set " + s + "+ as Custom Master List.";
                buttonSetCustomMaster.setText(text);
            }
        });


    }
}
